package com.gxa.controller;


import com.gxa.common.annotation.RequirePermission;
import com.gxa.common.base.Result;
import com.gxa.domain.entity.Cashier;
import com.gxa.service.CashierService;
import com.gxa.domain.vo.ProductCashierVO;
import com.gxa.domain.entity.Product;
import com.gxa.service.ProductService;
import com.gxa.service.PromotionProductService;
import com.gxa.service.ProductInfoService;
import com.gxa.domain.entity.ProductInfo;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;
import java.math.BigDecimal;

@RequestMapping("/cashier")
@RestController
@CrossOrigin(origins = "*")
@Tag(name = "收银", description = "收银信息管理相关接口")

public class CashierController {

    @Autowired
    private CashierService cashierService;
    @Autowired
    private ProductService productService;
    @Autowired
    private PromotionProductService promotionProductService;
    @Autowired
    private ProductInfoService productInfoService;

    @Operation(summary = "收银全查询")
    @RequirePermission("收银")
    @GetMapping("/findAll")//定义访问路径
    public Result findAll(){
        List<Cashier> cashierList = cashierService.findCashierAll();
        return Result.buildSuccess(cashierList);
    }

    @Operation(summary = "根据条码查询商品")
    @RequirePermission("收银")
    @GetMapping("/find")
    public Result find(Long barCode){
        if(barCode==null){
            return Result.buildFail(20001,"条形码不能为空!");
        }
        Cashier cashier = cashierService.findCashierByBarCode(barCode);
        return Result.buildSuccess(cashier);
    }

    /**
     * 收银扫码查商品+活动价VO
     */
    @GetMapping("/cashier/product-info")
    public Result<ProductCashierVO> getProductInfoForCashier(@RequestParam String barcode) {
        ProductInfo productInfo = productInfoService.getByBarcodeNo(barcode);
        if (productInfo == null) {
            return Result.buildFail(404, "商品不存在");
        }
        // 查Product表获取售价和库存
        Product product = null;
        if (productInfo.getSerialNo() != null) {
            product = productService.findProductById(productInfo.getSerialNo());
        }
        BigDecimal bestPrice = promotionProductService.getBestPromotionPrice(productInfo.getSerialNo() != null ? productInfo.getSerialNo().toString() : null, barcode);
        ProductCashierVO vo = new ProductCashierVO();
        vo.setProductName(productInfo.getProductName());
        vo.setBarcode(barcode);
        vo.setProductSerialNo(productInfo.getSerialNo() != null ? productInfo.getSerialNo().toString() : null);
        vo.setSellingPrice(product != null ? product.getSellingPrice() : null);
        vo.setPromotionPrice(bestPrice);
        vo.setStockQuantity(product != null ? product.getStockQuantity() : null);
        return Result.buildSuccess(vo);
    }


}
